import React, {Component} from 'react';
import { observable, action, autorun, computed } from 'mobx';
import {Tools, Bubble } from 'weaver-mobile';
import { SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import { RouteLayout, Reply, CKRichText, MapPage } from 'weaver-mobile-page';
import showTemplates from '../../components/outSign/record/ListTemplate';
import subTemplates from '../../components/resource/showTemplates/index';
import * as api from '../../apis/sign';
import * as resourceAPI from '../../apis/resource';
import BaseStore from '../BaseStore';
import {getLocation} from '../../util/jemUtil';
import MapUtil from '../../util/mapUtil';
import isEmpty from 'lodash/isEmpty';
import moment from 'moment';

const getLabel = Tools.getLabel;

const conditionUrl = '/api/hrm/kq/attendanceButton/getOutButtonCondition';
const subConditionUrl = '/api/public/browser/condition/1'

class OutSignStoreV2 extends BaseStore{
    //#region layout
    @observable _showSchedual = false;
    @computed get showSchedual(){return this._showSchedual}
    set showSchedual(v){this._showSchedual = v}

    @action setShowSchedual = () => {
        this.showSchedual = !this.showSchedual;
    }

    setHeaderRef = dom => this.headerRef = dom;
    //#endregion

    //#region 地图相关
    @observable mapUtil = new MapUtil();

    @action onMapTypeChangeHandle = async type => {
        //call change map type
        api.resetUserMap({user_last_map: type});
    }

    @action draw = () => {}

    @action onLocationChangeHandle = locationInfo => {
        this.selectedLocation = true;
        this.selectedLocationInfo = locationInfo;
        this.draw();
    }
    //#endregion

    //#region 模块初始化
    @observable _initialPage = 0;
    @computed get initialPage(){return this._initialPage}
    set initialPage(v){this._initialPage = v}

    @action clearData = async () => {
        this.selectedLocation = false;
    }

    @observable _outSignSetting = {};
    @computed get outSignSetting(){return this.toJS(this._outSignSetting)}
    set outSignSetting(v){this._outSignSetting = v}

    @action getOutSignSetting = async () => {
        const data = await api.getOutSignSetting();
        if(data.status == '1')
            this.outSignSetting = data;
        else
            Bubble.error(data.message);
    }
    
    @action init = async () => {
        //test
        // this.getOsInfo();
        //获取外勤设置
        this.getOutSignSetting();
        //获取基础信息
        const data = await this.getButtonBaseInfo();
        this.clearData();
    }
    //#endregion

    //#region 获取基础信息
    monitor = null;//刷新当前打卡时间计时器
    @observable _currTime = moment();//刷新当前打卡时间
    @computed get currTime(){return this.toJS(this._currTime)}
    set currTime(v){this._currTime = v}

    @observable _baseInfo = {};//基础信息
    @computed get baseInfo(){return this.toJS(this._baseInfo)}
    set baseInfo(v){this._baseInfo = v}

    @action getButtonBaseInfo = async () => {
        const data = await api.getButtonBaseInfo();
        if(data.status == '1' || data.status == null){
            delete data.status;
            this.baseInfo = data;
            const {timemillis} = data;
            this.currTime = (timemillis != null ? moment(new Date(timemillis)) : moment());
            this.clearMonitor();
            this.monitor = setInterval(() => {this.currTime = this.currTime.add(1, 'seconds')}, 1000);
        }else{
            Bubble.error(data.message);
        }
        return data;
    }

    @action clearMonitor = () => {this.monitor != null && clearInterval(this.monitor)}
    //#endregion

    //#region 获取设备信息以及定位信息
    deviceInfo = {};

    @observable _locationInfo = {};
    @computed get locationInfo(){return this.toJS(this._locationInfo)}
    set locationInfo(v){this._locationInfo = v}

    @observable _selectedLocationInfo = {};
    @computed get selectedLocationInfo(){return this.toJS(this._selectedLocationInfo)}
    set selectedLocationInfo(v){this._selectedLocationInfo = v}

    @computed get currentPosition(){
        if(this.selectedLocation)
            return this.selectedLocationInfo;
        return this.locationInfo;
    }

    @computed get hasLocationInfo(){
        const {longitude, latitude} = this.locationInfo;
        return longitude != null && longitude != '' && latitude != null && latitude != '';
    }

    @action onLocationChangedHandle = async locationInfo => {
        if(this.selectedLocation)
            return;
        if(locationInfo.status == '1' && isEmpty(locationInfo.address)){
            const regeoData = await this.regeo(locationInfo);
            Object.assign(locationInfo, regeoData);
        }
        this.locationInfo = locationInfo;
    }

    @action getLocationInfo = async callback => {
        this.Toast.loading('loading', 0);
        this.selectedLocation = false;
        this.locationInfo = await getLocation(this.mapUtil, this.onLocationChangedHandle);
        if(callback){
            callback();
            this.draw = callback;
        }
        this.Toast.hide();
    }
    //#endregion 

    //#region 附近位置
    @observable locationsLayoutStore = new RouteLayout.Store({ route: '/outSignV2', id: 'locations' });
    @observable selectedLocation = false;
    //#endregion

    //#region 外勤打卡
    @observable signLayoutStore = new RouteLayout.Store({ route: '/outSignV2', id: 'sign' });//外勤打卡路由
    //#endregion

    currentPage = 1; 
    pageSize = 20;
    dataTemp = {};
    resourceId;

    spinning = false;

    // @observable baseInfo = {};
    // @observable outButtonRange = {};
    
    @observable recordInitialPage = 0;
    @observable viewType = 0;//0.list 1.map
    
    @observable currentPositionData = {};
    @observable positionStatus = false;

    @observable showSchedual = false;

    @observable listViewStore = new ListViewPage.Store();
    @observable listDatas = [];
    @observable count = 0;

    @observable nearList = [];
    @observable selectedNearIndex = 0;

    @observable searchDate = this.moment().format('YYYY-MM-DD');

    @observable subordinates = {};

    monitorTabPage = () => {
        this.initialPage;
        if(this.initialPage == 1){
            this.setActiveTab(0);
        }
	}


    // monitor = autorun(this.monitorTabPage);
    
    getConditionParams = () => {
        let s = (this.resourceId == null ? this.advanceSearchPageStore : this.advanceSearchPageStore1);
        const {form: {formParams}} = s;
        return formParams;
    }

    getQueryParams = () => {
        const params = {
            ...this.getConditionParams(),
            pageIndex: this.currentPage,
            pageSize: this.pageSize
        }
        this.resourceId != null && Object.assign(params, {resourceId: this.resourceId});
        return params;
    }


    @action setActiveTab = index => {
        this.recordInitialPage = index;
        if(index == 0){
            this.viewType = 0;
            this.querySearchCondition();
        }
    }

    @action setViewType = v => this.viewType = v;

    @action cleanData = () => {
        this.currentPage = 1;
        this.listDatas.length = 0;
        this.dataTemp = {};
    }

    @action refreshData = (resourceId) => {
        this.resourceId = resourceId;
        this.listDatas.length = 0;
        this.dataTemp = {};
        this.setCurrentPage(1);
    }

    @action setCurrentPage = idx => {
        if(idx == null)
            this.currentPage++;
        else if(idx === this.currentPage && this.currentPage != 1){
            this.listViewStore.setState({hasMore: false, loading: false});
            return;
        } else{
            this.cleanData();
        }
        this.queryData(this.getQueryParams());
    }

    @action querySearchCondition = (resourceId) => {
        let s = (resourceId == null ? this.advanceSearchPageStore : this.advanceSearchPageStore1);
        s.getData({
            url: conditionUrl
        }).then(form => {
            this.doReset(resourceId);
            this.cleanData();
            this.refreshData(resourceId);
        });
    }

    @action doReset = (resourceId) => {
        let s = (resourceId == null ? this.advanceSearchPageStore : this.advanceSearchPageStore1);
        const {
            form
        } = s;
        form.resetFields();
    }

    @action queryData = (params) => {
        this.listViewStore.setState({
            loading: true
        });
        api.getOutSearchList({data: JSON.stringify({...params, order: 1})}).then(data => {
            if(data.status == '1')
                this.setListData(data);
        }, error => {});
    }

    @action doSearch = () => this.refreshData(this.resourceId);

    @action setListData = data => {
        const { count } = data;
        const datas = data.datas.map((d, index) => {
            return {
                ...d,
                imgList: d.attachment.map(v => `/weaver/weaver.file.FileDownload?fileid=${v}`)
            }
        });
        const { template } = showTemplates;
        this.count = count;
        this.listDatas = [...this.toJS(this.listDatas), ...datas];
        
        const dataSource = this.listViewStore.dataSource.cloneWithRows(this.toJS(this.listDatas));
        this.listViewStore.setState({
            nameKey: this.nameKey,
            rowKey: this.rowKey,
            data: this.listDatas,
            template: { template },
            dataSource,
            hasMore: datas.length > 0 && this.count >= this.pageSize,
            loading: false,
            isTable: false,
            getData: () => {}
        });
    }

    @action querySubordinates = (resource) => {
        this.subordinates = resource;
        this.viewType= 0;
        this.querySearchCondition(resource.id);
    }

    @action setSearchDate = (date, callback) => {
        this.searchDate = date;
        this.queryMapData(callback);
    }

    @action queryMapData = (callback) => {
        let params = this.getQueryParams();
        delete params.pageIndex;
        delete params.pageSize;
        const d = this.moment(this.toJS(this.searchDate)).format('YYYY-MM-DD');
        params = {...params, typeselectselect: '6', typeselectfrom: d, typeselectto: d};

        api.getOutSearchList({data: JSON.stringify(params)}).then(data => {
            if(data.status == '1'){
                if(data.datas.length == 0){
                    Bubble.warning(getLabel(83553, '暂无数据'));
                }
                callback && callback(data.datas);
            }
        }, error => {});
    }

    @observable subCurrentPage = 1;
    @observable subListDatas = [];
    @observable subCount = 0;
    @observable showPop = false;
    @observable alllevel = true;
    @observable subListViewStore = new ListViewPage.Store();
    queryResourceId;

    getSubConditionParams = () => {
        const {form: {formParams}} = this.subAdvanceSearchPageStore;
        return formParams;
    }

    getSubQueryParams = () => {
        let params = {
            cmd: 'search',
            mobileResourceId: this.queryResourceId,
            ...this.getSubConditionParams()
        };
        params.min = (this.subCurrentPage - 1) * this.pageSize + 1;
        params.max = this.subCurrentPage * this.pageSize;
        if (this.alllevel) {
            params.alllevel = 1;
        }
        return params;
    }

    @action initSubordinatePage = (resourceId) => {
        this.queryResourceId = resourceId;
        this.alllevel = true;
        this.querySubSearchCondition();
    }

    @action setShowPop = bool => this.showPop = bool;

    @action onPopoverSelectHandle = node => {
        this.alllevel = !this.alllevel;
        this.setSubCurrentPage(1);
        this.showPop = false;
    }

    @action querySubSearchCondition = () => {
        this.subAdvanceSearchPageStore.getData({
            url: subConditionUrl
        }).then(form => {
            this.doSubReset();
            this.cleanSubData();
            this.querySubData(this.getSubQueryParams());
        });
    }

    @action cleanSubData = () => {
        this.showPop = false;
        this.subCurrentPage = 1;
        this.subListDatas.length = 0;
    }

    @action refreshSubData = () => {
        this.subListDatas.length = 0;
        this.setSubCurrentPage(1);
    }

    @action setSubCurrentPage = idx => {
        if(idx == null)
            this.subCurrentPage++;
        else if(idx === this.subCurrentPage && this.subCurrentPage != 1){
            this.subListViewStore.setState({hasMore: false, loading: false});
            return;
        } else{
            this.cleanSubData();
        }
        this.querySubData(this.getSubQueryParams());
    }

    @action doSubReset = () => {
        const {
            form
        } = this.subAdvanceSearchPageStore;
        form.resetFields();
    }

    @action querySubData = (params) => {
        this.subListViewStore.setState({
            loading: true
        });
        resourceAPI.queryData(params).then(data => {
            const {
                datas
            } = data;
            if (Array.isArray(datas)) {
                this.setSubListData(data);
            }
        }, error => {});
    }

    @action setSubListData = data => {
        const {
            count,
            datas
        } = data;
        const {
            template
        } = subTemplates;
        this.subCount = count;
        this.subListDatas = [...this.toJS(this.subListDatas), ...datas];

        const dataSource = this.subListViewStore.dataSource.cloneWithRows(this.toJS(this.subListDatas));
        this.subListViewStore.setState({
            nameKey: this.nameKey,
            rowKey: this.rowKey,
            data: this.subListDatas,
            template: {
                template
            },
            dataSource,
            hasMore: datas.length > 0 && this.subCount >= this.pageSize,
            loading: false,
            isTable: false,
            getData: () => {}
        });
    }

    @action doQuickSearch = () => {
        this.cleanSubData();
        this.querySubData(this.getSubQueryParams());
    }

    @action onQuickSearchChangeHandle = v => {
        const {
            form
        } = this.subAdvanceSearchPageStore;
        form.updateField('lastname', v.toString());
    }

    @action onClearSearchCondition = () => {
        this.onQuickSearchChangeHandle('');
        this.doQuickSearch();
    }
}

export const outSignStoreV2 = new OutSignStoreV2(); 